﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Data.OleDb;
using System.Threading;
using Microsoft;
using Microsoft.Office.Interop.Excel;
using WindowsFormsApplication4.src;

namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll")]
        private static extern bool
        SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
        [DllImport("user32.dll")]
        private static extern bool IsIconic(IntPtr hWnd);
        // 消息函数
        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string strclassName, string strWindowName);
        [DllImportAttribute("user32.dll")]
        //public static extern string SendMessage(IntPtr hWnd, int Msg, string wParam, string lParam);
        private static extern int SendMessage(IntPtr hWnd,int Msg, IntPtr wParam, string lParam); 

        [DllImport("user32.dll", EntryPoint = "FindWindowEx")]
        private extern static IntPtr FindWindowEx(IntPtr parnet, IntPtr child, string strclaa, string FrmText);
        [DllImport("user32")]
        private extern static int GetWindowText(IntPtr hWnd, StringBuilder ipString, int nMaxCount);
        [DllImport("user32.dll")]
        static extern int GetClassName(IntPtr Handle, [Out] StringBuilder ClassName, int MaxCount);
 

        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MAXIMIZE = 0xF030;
        public const int SC_CLOSE = 61536;
        public const int SC_ACTIVATE = 0x05;
        public const int WM_SETTEXT = 0x000C;
        public const int WM_GETTEXT = 0x000D;

        public Dictionary<string, object> decObjects;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {

            Process[] processes = Process.GetProcessesByName("WindowsFormsApplication3.vshost");
            LogHelper.WriteLog(typeof(Form1), "获取进程句柄");
            if (processes.Length > 0)
            {
                IntPtr hWnd = processes[0].MainWindowHandle; 
                SetForegroundWindow(hWnd);//激活该线程，并将该程序置顶

                //获取所有子类的类名
                List<IntPtr> list = GetChildHandles(hWnd, null);
                
                List<string> strList = new List<string>();
                foreach (IntPtr intp in list)
                {
                    StringBuilder className = new StringBuilder(256);
                    GetClassName(intp, className, className.Capacity);
                    if (className.ToString().Contains("EDIT") )
                    {
                        //遍历 找到input文本框的 Class
                        strList.Add(className.ToString());
                    }
                }

                //根据句柄向其他文本框发送消息
                IntPtr childHWnd = FindWindowEx(hWnd, new IntPtr(), strList[0], null);
                LogHelper.WriteLog(typeof(Form1), "文本框Class__"+strList[0]);
                //SendMessage(childHWnd, WM_SETTEXT, (IntPtr)0, "hashi");
                //根据句柄向其他文本框发送消息 end
                
               /**
                * 读取Excel中的数据并将其分层两种
                * 1.自动往表头新增数据
                * 2.循环自动往表体中新增数据
                * 注：现在先做每输入一个值都执行【enter】操作
                * 
                **/
                
                //得到导入的数据
                if(null != decObjects){
                    //表头数据录入
                    List<string> decHead = (List<string>) decObjects["decHead"];
                    List<List<string>> decLists = (List<List<string>>)decObjects["decLists"];

                    foreach (string value in decHead) {
                        if (null == value || value.Length < 1)
                        {
                            SendKeys.Send("{ENTER}");
                        }else{
                            SendKeys.Send(value);//模拟键盘输入值
                            SendKeys.Send("{ENTER}");//模拟键盘输入回车键
                        }
                    }

                    foreach(List<string> decList in decLists){
                        foreach (string value in decList)
                        {
                            if (null == value || value.Length < 1)
                            {
                                SendKeys.Send("{TAB}");
                            }
                            else
                            {
                                SendKeys.Send(value);//模拟键盘输入值
                                SendKeys.Send("{TAB}");//模拟键盘输入回车键
                            }
                        }
                        Thread.Sleep(1000);
                    }

                }

                
                                              
            }
        }

        public static IntPtr GetChildHandle(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass)
        {
            return FindWindowEx(hwndParent, hwndChildAfter, lpszClass, null);
        } 

        public static List<IntPtr> GetChildHandles(IntPtr hwndParent, string className)
        {
            List<IntPtr> resultList = new List<IntPtr>();
            for (IntPtr hwndClient = GetChildHandle(hwndParent, IntPtr.Zero, null); hwndClient != IntPtr.Zero; hwndClient = GetChildHandle(hwndParent, hwndClient, className))
            {
                resultList.Add(hwndClient);
            }
            return resultList;
        } 

        /// <summary>
        /// 点击【导入数据】 时，解析Excel表中的内容
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "文档(*.xls;*.xlsx)|*.xls;*.xlsx";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if (openFileDialog1.FileName != "")
                {
                    this.textBox1.Text = openFileDialog1.FileName;
                }
            }
        }

        /// <summary>
        /// 解析excle
        ///  1.报关单表头信息，list
        ///  2.报关单表体信息 list<list>
        ///  返回一个map
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            object missing = System.Reflection.Missing.Value;
            string filepath = this.textBox1.Text;
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            if(excel != null){
                excel.Visible = false;
                excel.UserControl = true;
                //以已读的形式打开Excel文件
                Workbook wb = excel.Application.Workbooks.Open(filepath, missing, true, missing, missing, missing,missing, missing, missing, true, missing, missing, missing, missing, missing);

                /**
                * 读取报关单表头信息 
                **/
                Worksheet headWs = (Worksheet)wb.Worksheets.get_Item(1);//取得第一个工作薄
              //  int headRowsCount = headWs.UsedRange.Cells.Rows.Count;//得到总行数
                int headColsCount = headWs.UsedRange.Cells.Columns.Count;//得到总列数
                //做一些简单验证尚未完成 TODO
                List<string> decHeadList = new List<string>();
                for (int j = 1; j < headColsCount + 1; j++)
                {
                     string temp = (string)((Range)headWs.Cells[2,j]).Text;
                     decHeadList.Add(temp);
                }

                foreach (string s in decHeadList)
                {
                    Console.WriteLine(s);
                }
                
                /**
                 * 读取报关单表体信息
                 **/
                Worksheet listWs = (Worksheet)wb.Worksheets.get_Item(2);
                int listRowsCount = listWs.UsedRange.Cells.Count;
                int listColsCount = listWs.UsedRange.Columns.Count;
                //TODO  做一个简单验证
                List<List<string>> decLists = new List<List<string>>();

                for (int i = 1; i < listRowsCount+1;i++ )
                {
                    List<string> temp = new List<string>();
                    for (int j = 1; j < listColsCount + 1;j++ )
                    {
                        string value = (string)((Range)listWs.Cells[i, j]).Text;
                        temp.Add(value);
                    }
                    decLists.Add(temp);
                }

                decObjects = new Dictionary<string, object>();
                decObjects.Add("decHead", decHeadList);
                decObjects.Add("decLists", decLists);
            }
        }

        
        
        //获取表格中的数据
        //public static DataTable ExcelToDataTble(string strExcelFileName, string strSheetName) { 
            
        //    //源的定义
        //    //string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strExcelFileName + ";"
        //    //    + "Extended Properties=\"Excel 12.0;HDR=YES\"";
        //    string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + strExcelFileName + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'"; //此連接可以操作.xls與.xlsx文件
        //    //Sql 语句
        //    string strExcel = string.Format("select * from [{0}$]", strSheetName);
        //    //string strExcel = "select * from [sheet1$]";

        //    //定义存放的数据表
        //    DataSet ds = new DataSet();
        //    //连接数据源
        //    OleDbConnection conn = new OleDbConnection(strConn);
        //    conn.Open();
        //    //适配到数据源
        //    OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel,strConn);
        //    adapter.Fill(ds,strSheetName);

        //    conn.Close();
        //    return ds.Tables[strSheetName];
            
        //}
        
       
    }

}
